<!-- HTML header for doxygen 1.8.6-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=9">
<meta name="generator" content="Doxygen 1.8.13">
<title>OpenCV:加载Caffe框架模型</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon">
<link href="../../tabs.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<script type="text/javascript" src="../../tutorial-utils.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
//<![CDATA[
MathJax.Hub.Config(
{
  TeX: {
      Macros: {
          matTT: [ "\\[ \\left|\\begin{array}{ccc} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{array}\\right| \\]", 9],
          fork: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ \\end{array} \\right.", 4],
          forkthree: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ \\end{array} \\right.", 6],
          forkfour: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ #7 & \\mbox{#8}\\\\ \\end{array} \\right.", 8],
          vecthree: ["\\begin{bmatrix} #1\\\\ #2\\\\ #3 \\end{bmatrix}", 3],
          vecthreethree: ["\\begin{bmatrix} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{bmatrix}", 9],
          cameramatrix: ["#1 = \\begin{bmatrix} f_x & 0 & c_x\\\\ 0 & f_y & c_y\\\\ 0 & 0 & 1 \\end{bmatrix}", 1],
          distcoeffs: ["(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \\tau_x, \\tau_y]]]]) \\text{ of 4, 5, 8, 12 or 14 elements}"],
          distcoeffsfisheye: ["(k_1, k_2, k_3, k_4)"],
          hdotsfor: ["\\dots", 1],
          mathbbm: ["\\mathbb{#1}", 1],
          bordermatrix: ["\\matrix{#1}", 1]
      }
  }
}
);
//]]>
</script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js"></script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css">
<link href="../../stylesheet.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<!--#include virtual="/google-search.html"-->
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="../../opencv-logo-small.png"></td>
  <td style="padding-left: 0.5em;">
   <div id="projectname">OpenCV
   &#160;<span id="projectnumber">4.5.2</span>
   </div>
   <div id="projectbrief">Open Source Computer Vision</div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
$(function() {
  initMenu('../../',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div id="nav-path" class="navpath">
  <ul>
<li class="navelem"><a class="el" href="../../d9/df8/tutorial_root.html">OpenCV Tutorials</a></li><li class="navelem"><a class="el" href="../../d2/d58/tutorial_table_of_content_dnn.html">Deep Neural Networks (dnn module)</a></li>  </ul>
</div>
</div><!-- top -->
<div class="header">
  <div class="headertitle">
<div class="title">加载Caffe框架模型</div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p><b>下一个教程:</b> <a class="el" href="../../de/d37/tutorial_dnn_halide.html">How to enable Halide backend for improve efficiency</a></p>
<table class="doxtable">
<tr>
<th align="right"></th><th align="left"></th></tr>
<tr>
<td align="right">原作者</td><td align="left">Vitaliy Lyudvichenko</td></tr>
<tr>
<td align="right">兼容性</td><td align="left">OpenCV &gt;= 3.3 </td></tr>
</table>
<h2>介绍</h2>
<p>在本教程中,您将学习如何使用  opencv_dnn 模块进行图像分类,方法是使用来自<a href="http://caffe.berkeleyvision.org/model_zoo.html">Caffe model zoo</a>.</p>
<p>我们将在下图中演示此示例的结果.</p><div class="image">
<img src="../../space_shuttle.jpg" alt="space_shuttle.jpg">
<div class="caption">伯兰航天飞机</div></div>
 <h2>源代码</h2>
<p>我们将使用示例应用程序中的片段,这些片段可以下载<a href="https://github.com/opencv/opencv/blob/master/samples/dnn/classification.cpp">在这里</a>.</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &lt;fstream&gt;</span></div><div class="line"><span class="preprocessor">#include &lt;sstream&gt;</span></div><div class="line"></div><div class="line"><span class="preprocessor">#include &lt;<a class="code" href="../../d9/d8c/dnn_8hpp.html">opencv2/dnn.hpp</a>&gt;</span></div><div class="line"><span class="preprocessor">#include &lt;<a class="code" href="../../d1/d4f/imgproc_2include_2opencv2_2imgproc_8hpp.html">opencv2/imgproc.hpp</a>&gt;</span></div><div class="line"><span class="preprocessor">#include &lt;<a class="code" href="../../d4/dd5/highgui_8hpp.html">opencv2/highgui.hpp</a>&gt;</span></div><div class="line"></div><div class="line"><span class="preprocessor">#include &quot;common.hpp&quot;</span></div><div class="line"></div><div class="line">std::string keys =</div><div class="line">    <span class="stringliteral">&quot;{ help  h          | | Print help message. }&quot;</span></div><div class="line">    <span class="stringliteral">&quot;{ @alias           | | An alias name of model to extract preprocessing parameters from models.yml file. }&quot;</span></div><div class="line">    <span class="stringliteral">&quot;{ zoo              | models.yml | An optional path to file with preprocessing parameters }&quot;</span></div><div class="line">    <span class="stringliteral">&quot;{ input i          | | Path to input image or video file. Skip this argument to capture frames from a camera.}&quot;</span></div><div class="line">    <span class="stringliteral">&quot;{ initial_width    | 0 | Preprocess input image by initial resizing to a specific width.}&quot;</span></div><div class="line">    <span class="stringliteral">&quot;{ initial_height   | 0 | Preprocess input image by initial resizing to a specific height.}&quot;</span></div><div class="line">    <span class="stringliteral">&quot;{ std              | 0.0 0.0 0.0 | Preprocess input image by dividing on a standard deviation.}&quot;</span></div><div class="line">    <span class="stringliteral">&quot;{ crop             | false | Preprocess input image by center cropping.}&quot;</span></div><div class="line">    <span class="stringliteral">&quot;{ framework f      | | Optional name of an origin framework of the model. Detect it automatically if it does not set. }&quot;</span></div><div class="line">    <span class="stringliteral">&quot;{ classes          | | Optional path to a text file with names of classes. }&quot;</span></div><div class="line">    <span class="stringliteral">&quot;{ backend          | 0 | Choose one of computation backends: &quot;</span></div><div class="line">                            <span class="stringliteral">&quot;0: automatically (by default), &quot;</span></div><div class="line">                            <span class="stringliteral">&quot;1: Halide language (http://halide-lang.org/), &quot;</span></div><div class="line">                            <span class="stringliteral">&quot;2: Intel&#39;s Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), &quot;</span></div><div class="line">                            <span class="stringliteral">&quot;3: OpenCV implementation }&quot;</span></div><div class="line">    <span class="stringliteral">&quot;{ target           | 0 | Choose one of target computation devices: &quot;</span></div><div class="line">                            <span class="stringliteral">&quot;0: CPU target (by default), &quot;</span></div><div class="line">                            <span class="stringliteral">&quot;1: OpenCL, &quot;</span></div><div class="line">                            <span class="stringliteral">&quot;2: OpenCL fp16 (half-float precision), &quot;</span></div><div class="line">                            <span class="stringliteral">&quot;3: VPU }&quot;</span>;</div><div class="line"></div><div class="line"><span class="keyword">using namespace </span><a class="code" href="../../d2/d75/namespacecv.html">cv</a>;</div><div class="line"><span class="keyword">using namespace </span>dnn;</div><div class="line"></div><div class="line">std::vector&lt;std::string&gt; classes;</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> main(<span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>** argv)</div><div class="line">{</div><div class="line">    <a class="code" href="../../d0/d2e/classcv_1_1CommandLineParser.html">CommandLineParser</a> parser(argc, argv, keys);</div><div class="line"></div><div class="line">    <span class="keyword">const</span> std::string modelName = parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;(<span class="stringliteral">&quot;@alias&quot;</span>);</div><div class="line">    <span class="keyword">const</span> std::string zooFile = parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;(<span class="stringliteral">&quot;zoo&quot;</span>);</div><div class="line"></div><div class="line">    keys += genPreprocArguments(modelName, zooFile);</div><div class="line"></div><div class="line">    parser = <a class="code" href="../../d0/d2e/classcv_1_1CommandLineParser.html">CommandLineParser</a>(argc, argv, keys);</div><div class="line">    parser.about(<span class="stringliteral">&quot;Use this script to run classification deep learning networks using OpenCV.&quot;</span>);</div><div class="line">    <span class="keywordflow">if</span> (argc == 1 || parser.has(<span class="stringliteral">&quot;help&quot;</span>))</div><div class="line">    {</div><div class="line">        parser.printMessage();</div><div class="line">        <span class="keywordflow">return</span> 0;</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keywordtype">int</span> rszWidth = parser.get&lt;<span class="keywordtype">int</span>&gt;(<span class="stringliteral">&quot;initial_width&quot;</span>);</div><div class="line">    <span class="keywordtype">int</span> rszHeight = parser.get&lt;<span class="keywordtype">int</span>&gt;(<span class="stringliteral">&quot;initial_height&quot;</span>);</div><div class="line">    <span class="keywordtype">float</span> <a class="code" href="../../d6/d84/namespacecv_1_1quality_1_1quality__utils.html#ae55d1c89ff5761730174745401162743">scale</a> = parser.get&lt;<span class="keywordtype">float</span>&gt;(<span class="stringliteral">&quot;scale&quot;</span>);</div><div class="line">    <a class="code" href="../../d1/da0/classcv_1_1Scalar__.html">Scalar</a> <a class="code" href="../../d2/de8/group__core__array.html#ga191389f8a0e58180bb13a727782cd461">mean</a> = parser.get&lt;<a class="code" href="../../d1/da0/classcv_1_1Scalar__.html">Scalar</a>&gt;(<span class="stringliteral">&quot;mean&quot;</span>);</div><div class="line">    <a class="code" href="../../d1/da0/classcv_1_1Scalar__.html">Scalar</a> <a class="code" href="../../d8/dcc/namespacestd.html">std</a> = parser.get&lt;<a class="code" href="../../d1/da0/classcv_1_1Scalar__.html">Scalar</a>&gt;(<span class="stringliteral">&quot;std&quot;</span>);</div><div class="line">    <span class="keywordtype">bool</span> swapRB = parser.get&lt;<span class="keywordtype">bool</span>&gt;(<span class="stringliteral">&quot;rgb&quot;</span>);</div><div class="line">    <span class="keywordtype">bool</span> <a class="code" href="../../d6/d91/group__gapi__transform.html#gae72ac2d6fec8d4e636a7d72d37e70895">crop</a> = parser.get&lt;<span class="keywordtype">bool</span>&gt;(<span class="stringliteral">&quot;crop&quot;</span>);</div><div class="line">    <span class="keywordtype">int</span> inpWidth = parser.get&lt;<span class="keywordtype">int</span>&gt;(<span class="stringliteral">&quot;width&quot;</span>);</div><div class="line">    <span class="keywordtype">int</span> inpHeight = parser.get&lt;<span class="keywordtype">int</span>&gt;(<span class="stringliteral">&quot;height&quot;</span>);</div><div class="line">    <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> model = <a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">findFile</a>(parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;(<span class="stringliteral">&quot;model&quot;</span>));</div><div class="line">    <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> config = <a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">findFile</a>(parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;(<span class="stringliteral">&quot;config&quot;</span>));</div><div class="line">    <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> framework = parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;(<span class="stringliteral">&quot;framework&quot;</span>);</div><div class="line">    <span class="keywordtype">int</span> backendId = parser.get&lt;<span class="keywordtype">int</span>&gt;(<span class="stringliteral">&quot;backend&quot;</span>);</div><div class="line">    <span class="keywordtype">int</span> targetId = parser.get&lt;<span class="keywordtype">int</span>&gt;(<span class="stringliteral">&quot;target&quot;</span>);</div><div class="line"></div><div class="line">    <span class="comment">// Open file with classes names.</span></div><div class="line">    <span class="keywordflow">if</span> (parser.has(<span class="stringliteral">&quot;classes&quot;</span>))</div><div class="line">    {</div><div class="line">        std::string file = parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;(<span class="stringliteral">&quot;classes&quot;</span>);</div><div class="line">        std::ifstream ifs(file.c_str());</div><div class="line">        <span class="keywordflow">if</span> (!ifs.is_open())</div><div class="line">            <a class="code" href="../../db/de0/group__core__utils.html#ga5b48c333c777666e076bd7052799f891">CV_Error</a>(<a class="code" href="../../d1/d0d/namespacecv_1_1Error.html#a759fa1af92f7aa7377c76ffb142abccaacf93e97abba2e7defa74fe5b99e122ac">Error::StsError</a>, <span class="stringliteral">&quot;File &quot;</span> + file + <span class="stringliteral">&quot; not found&quot;</span>);</div><div class="line">        std::string <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga7078a9fae8c7e7d13d24dac2520ae4a2">line</a>;</div><div class="line">        <span class="keywordflow">while</span> (std::getline(ifs, line))</div><div class="line">        {</div><div class="line">            classes.push_back(line);</div><div class="line">        }</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keywordflow">if</span> (!parser.check())</div><div class="line">    {</div><div class="line">        parser.printErrors();</div><div class="line">        <span class="keywordflow">return</span> 1;</div><div class="line">    }</div><div class="line">    <a class="code" href="../../db/de0/group__core__utils.html#gaf62bcd90f70e275191ab95136d85906b">CV_Assert</a>(!model.empty());</div><div class="line"></div><div class="line">    Net net = <a class="code" href="../../d6/d0f/group__dnn.html#ga3b34fe7a29494a6a4295c169a7d32422">readNet</a>(model, config, framework);</div><div class="line">    net.setPreferableBackend(backendId);</div><div class="line">    net.setPreferableTarget(targetId);</div><div class="line"></div><div class="line">    <span class="comment">// Create a window</span></div><div class="line">    <span class="keyword">static</span> <span class="keyword">const</span> std::string kWinName = <span class="stringliteral">&quot;Deep learning image classification in OpenCV&quot;</span>;</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5afdf8410934fd099df85c75b2e0888b">namedWindow</a>(kWinName, <a class="code" href="../../d0/d90/group__highgui__window__flags.html#ggabf7d2c5625bc59ac130287f925557ac3a29e45c5af696f73ce5e153601e5ca0f1">WINDOW_NORMAL</a>);</div><div class="line"></div><div class="line">    <a class="code" href="../../d8/dfe/classcv_1_1VideoCapture.html">VideoCapture</a> cap;</div><div class="line">    <span class="keywordflow">if</span> (parser.has(<span class="stringliteral">&quot;input&quot;</span>))</div><div class="line">        cap.<a class="code" href="../../d8/dfe/classcv_1_1VideoCapture.html#a614a1702e15f42ede5100014ce7f48ed">open</a>(parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;(<span class="stringliteral">&quot;input&quot;</span>));</div><div class="line">    <span class="keywordflow">else</span></div><div class="line">        cap.<a class="code" href="../../d8/dfe/classcv_1_1VideoCapture.html#a614a1702e15f42ede5100014ce7f48ed">open</a>(0);</div><div class="line"></div><div class="line">    <span class="comment">// Process frames.</span></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> frame, blob;</div><div class="line">    <span class="keywordflow">while</span> (<a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>(1) &lt; 0)</div><div class="line">    {</div><div class="line">        cap &gt;&gt; frame;</div><div class="line">        <span class="keywordflow">if</span> (frame.empty())</div><div class="line">        {</div><div class="line">            <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>();</div><div class="line">            <span class="keywordflow">break</span>;</div><div class="line">        }</div><div class="line"></div><div class="line">        <span class="keywordflow">if</span> (rszWidth != 0 &amp;&amp; rszHeight != 0)</div><div class="line">        {</div><div class="line">            <a class="code" href="../../da/d54/group__imgproc__transform.html#ga47a974309e9102f5f08231edc7e7529d">resize</a>(frame, frame, <a class="code" href="../../dc/d84/group__core__basic.html#ga346f563897249351a34549137c8532a0">Size</a>(rszWidth, rszHeight));</div><div class="line">        }</div><div class="line"></div><div class="line">        <a class="code" href="../../d6/d0f/group__dnn.html#ga29f34df9376379a603acd8df581ac8d7">blobFromImage</a>(frame, blob, scale, <a class="code" href="../../dc/d84/group__core__basic.html#ga346f563897249351a34549137c8532a0">Size</a>(inpWidth, inpHeight), mean, swapRB, crop);</div><div class="line"></div><div class="line">        <span class="comment">// Check std values.</span></div><div class="line">        <span class="keywordflow">if</span> (std.val[0] != 0.0 &amp;&amp; std.val[1] != 0.0 &amp;&amp; std.val[2] != 0.0)</div><div class="line">        {</div><div class="line">            <span class="comment">// Divide blob by std.</span></div><div class="line">            <a class="code" href="../../d2/de8/group__core__array.html#ga6db555d30115642fedae0cda05604874">divide</a>(blob, std, blob);</div><div class="line">        }</div><div class="line"></div><div class="line">        net.setInput(blob);</div><div class="line">        <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> prob = net.forward();</div><div class="line"></div><div class="line">        <a class="code" href="../../db/d4e/classcv_1_1Point__.html">Point</a> classIdPoint;</div><div class="line">        <span class="keywordtype">double</span> confidence;</div><div class="line">        <a class="code" href="../../d2/de8/group__core__array.html#gab473bf2eb6d14ff97e89b355dac20707">minMaxLoc</a>(prob.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a4eb96e3251417fa88b78e2abd6cfd7d8">reshape</a>(1, 1), 0, &amp;confidence, 0, &amp;classIdPoint);</div><div class="line">        <span class="keywordtype">int</span> classId = classIdPoint.<a class="code" href="../../db/d4e/classcv_1_1Point__.html#a4c96fa7bdbfe390be5ed356edb274ff3">x</a>;</div><div class="line"></div><div class="line">        <span class="comment">// Put efficiency information.</span></div><div class="line">        std::vector&lt;double&gt; layersTimes;</div><div class="line">        <span class="keywordtype">double</span> freq = <a class="code" href="../../db/de0/group__core__utils.html#ga705441a9ef01f47acdc55d87fbe5090c">getTickFrequency</a>() / 1000;</div><div class="line">        <span class="keywordtype">double</span> t = net.getPerfProfile(layersTimes) / freq;</div><div class="line">        std::string label = format(<span class="stringliteral">&quot;Inference time: %.2f ms&quot;</span>, t);</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga5126f47f883d730f633d74f07456c576">putText</a>(frame, label, <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(0, 15), <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gga0f9314ea6e35f99bb23f29567fc16e11afff8b973668df2e4028dddc5274310c9">FONT_HERSHEY_SIMPLEX</a>, 0.5, <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0, 255, 0));</div><div class="line"></div><div class="line">        <span class="comment">// Print predicted class.</span></div><div class="line">        label = format(<span class="stringliteral">&quot;%s: %.4f&quot;</span>, (classes.empty() ? format(<span class="stringliteral">&quot;Class #%d&quot;</span>, classId).c_str() :</div><div class="line">                                                      classes[classId].c_str()),</div><div class="line">                                   confidence);</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga5126f47f883d730f633d74f07456c576">putText</a>(frame, label, <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(0, 40), <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gga0f9314ea6e35f99bb23f29567fc16e11afff8b973668df2e4028dddc5274310c9">FONT_HERSHEY_SIMPLEX</a>, 0.5, <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0, 255, 0));</div><div class="line"></div><div class="line">        <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(kWinName, frame);</div><div class="line">    }</div><div class="line">    <span class="keywordflow">return</span> 0;</div><div class="line">}</div></div><!-- fragment --><h2>解释</h2>
<ol type="1">
<li><p class="startli">首先,下载GoogLeNet模型文件:<a href="https://github.com/opencv/opencv_extra/blob/master/testdata/dnn/bvlc_googlenet.prototxt">bvlc_googlenet.prototxt</a>和<a href="http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel">bvlc_googlenet.caffemodel</a></p>
<p class="startli">你还需要文件名<a href="http://image-net.org/challenges/LSVRC/2012/browse-synsets">ILSVRC2012</a>课程:<a href="https://github.com/opencv/opencv/blob/master/samples/data/dnn/classification_classes_ILSVRC2012.txt">classification_classes_ILSVRC2012.txt</a>.</p>
<p class="startli">将这些文件放入本程序示例的工作目录中.</p>
</li>
<li>使用.prototxt和.caffemodel文件的路径读取和初始化网络<div class="fragment"><div class="line">    Net net = <a class="code" href="../../d6/d0f/group__dnn.html#ga3b34fe7a29494a6a4295c169a7d32422">readNet</a>(model, config, framework);</div><div class="line">    net.setPreferableBackend(backendId);</div><div class="line">    net.setPreferableTarget(targetId);</div></div><!-- fragment -->你可以跳过争论<code>framework</code>如果其中一个文件<code>model</code>或<code>config</code>有一个扩展名<code>.caffemodel</code>或<code>.prototxt</code>. 这种方式起作用<a class="el" href="../../d6/d0f/group__dnn.html#ga3b34fe7a29494a6a4295c169a7d32422" title="Read deep learning network represented in one of the supported formats. ">cv::dnn::readNet</a>可以自动检测模型的格式.</li>
<li><p class="startli">读取输入图像并转换为GoogleNet可接受的blob</p><div class="fragment"><div class="line">    VideoCapture cap;</div><div class="line">    <span class="keywordflow">if</span> (parser.has(<span class="stringliteral">&quot;input&quot;</span>))</div><div class="line">        cap.<a class="code" href="../../d8/dfe/classcv_1_1VideoCapture.html#a614a1702e15f42ede5100014ce7f48ed">open</a>(parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;(<span class="stringliteral">&quot;input&quot;</span>));</div><div class="line">    <span class="keywordflow">else</span></div><div class="line">        cap.open(0);</div></div><!-- fragment --><p> <a class="el" href="../../d8/dfe/classcv_1_1VideoCapture.html" title="Class for video capturing from video files, image sequences or cameras. ">cv::VideoCapture</a>可以加载图像和视频.</p>
<div class="fragment"><div class="line">        <a class="code" href="../../d6/d0f/group__dnn.html#ga29f34df9376379a603acd8df581ac8d7">blobFromImage</a>(frame, blob, scale, <a class="code" href="../../dc/d84/group__core__basic.html#ga346f563897249351a34549137c8532a0">Size</a>(inpWidth, inpHeight), mean, swapRB, crop);</div><div class="line"></div><div class="line">        <span class="comment">// Check std values.</span></div><div class="line">        <span class="keywordflow">if</span> (std.val[0] != 0.0 &amp;&amp; std.val[1] != 0.0 &amp;&amp; std.val[2] != 0.0)</div><div class="line">        {</div><div class="line">            <span class="comment">// Divide blob by std.</span></div><div class="line">            <a class="code" href="../../d2/de8/group__core__array.html#ga6db555d30115642fedae0cda05604874">divide</a>(blob, std, blob);</div><div class="line">        }</div></div><!-- fragment --><p>我们将图像转换成一个4维的blob(所谓的批处理),并且<code>1x3x224x224</code>在应用必要的预处理(如调整大小和平均减法)后形成<code>(-104, -117, -123)</code>对于每个蓝色、绿色和红色通道,相应地使用<a class="el" href="../../d6/d0f/group__dnn.html#ga29f34df9376379a603acd8df581ac8d7" title="Creates 4-dimensional blob from image. Optionally resizes and crops image from center, subtract mean values, scales values by scalefactor, swap Blue and Red channels. ">cv::dnn::blobFromImage</a>功能.</p>
</li>
<li>将blob传递到网络<div class="fragment"><div class="line">        net.setInput(blob);</div></div><!-- fragment --></li>
<li>向前传递<div class="fragment"><div class="line">        Mat prob = net.forward();</div></div><!-- fragment -->在前向传递期间,计算每个网络层的输出,但在本例中,我们只需要最后一层的输出.</li>
<li>确定最佳层级<div class="fragment"><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a> classIdPoint;</div><div class="line">        <span class="keywordtype">double</span> confidence;</div><div class="line">        <a class="code" href="../../d2/de8/group__core__array.html#gab473bf2eb6d14ff97e89b355dac20707">minMaxLoc</a>(prob.reshape(1, 1), 0, &amp;confidence, 0, &amp;classIdPoint);</div><div class="line">        <span class="keywordtype">int</span> classId = classIdPoint.x;</div></div><!-- fragment -->我们将包含1000个ILSVRC2012图像类中每个类的概率的网络输出放到<code>prob</code>blob.并求出该元素中具有最大值的元素的索引.此索引对应于图像的类.</li>
<li>从命令行运行示例<div class="fragment"><div class="line">./example_dnn_classification --model=bvlc_googlenet.caffemodel --config=bvlc_googlenet.prototxt --width=224 --height=224 --classes=classification_classes_ILSVRC2012.txt --input=space_shuttle.jpg --mean=&quot;104 117 123&quot;</div></div><!-- fragment -->对于我们的形象,我们得到了阶级的预测<code>space shuttle</code>有99%以上的把握.</li>
</ol>
</div></div><!-- contents -->
<!-- HTML footer for doxygen 1.8.6-->
<!-- start footer part -->
<hr class="footer"><address class="footer"><small>Generated on Fri Apr 2 2021 11:36:34 for OpenCV by &#160;zsz<a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen">
</a> 1.8.13
</small></address>
<script type="text/javascript">
//<![CDATA[
addTutorialsButtons();
//]]>
</script>
</body>
</html>
